package com.onlineMIS.ORM.DAO.headQ.supplier.purchase;


import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.math.BigDecimal;
import java.sql.Timestamp;
import java.text.DateFormat;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.UUID;

import com.onlineMIS.ORM.entity.base.BaseOrder;
import com.onlineMIS.ORM.entity.chainS.sales.PurchaseOrderTemplate;
import com.onlineMIS.ORM.entity.headQ.SQLServer.Billdraftidx;
import com.onlineMIS.ORM.entity.headQ.SQLServer.PriceMS;
import com.onlineMIS.ORM.entity.headQ.SQLServer.ProductsMS;
import com.onlineMIS.ORM.entity.headQ.SQLServer.Salemanagebilldrf;
import com.onlineMIS.ORM.entity.headQ.SQLServer.buymanagebilldrf;
import com.onlineMIS.ORM.entity.headQ.SQLServer.storemanagebilldrf;
import com.onlineMIS.ORM.entity.headQ.barcodeGentor.Brand;
import com.onlineMIS.ORM.entity.headQ.barcodeGentor.Category;
import com.onlineMIS.ORM.entity.headQ.barcodeGentor.Color;
import com.onlineMIS.ORM.entity.headQ.barcodeGentor.HeadqEntityTag;

import org.apache.catalina.User;
import org.springframework.beans.BeanUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.math.NumberUtils;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.hibernate.Criteria;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.MatchMode;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;
import org.springframework.aop.ThrowsAdvice;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.onlineMIS.ORM.DAO.Response;
import com.onlineMIS.ORM.DAO.headQ.SQLServer.BilldraftidxDAOImpl;
import com.onlineMIS.ORM.DAO.headQ.SQLServer.BuymanagebilldrfDAOImpl;
import com.onlineMIS.ORM.DAO.headQ.SQLServer.ProductsMSDAOImpl;
import com.onlineMIS.ORM.DAO.headQ.SQLServer.StoremanagebilldrfDAOImpl;
import com.onlineMIS.ORM.DAO.headQ.barCodeGentor.ProductBarcodeDaoImpl;
import com.onlineMIS.ORM.DAO.headQ.barCodeGentor.ProductDaoImpl;
import com.onlineMIS.ORM.DAO.headQ.inventory.InventoryOrderDAOImpl;
import com.onlineMIS.ORM.DAO.headQ.inventory.InventoryService;
import com.onlineMIS.ORM.DAO.headQ.inventoryFlow.HeadQInventoryStockDAOImpl;
import com.onlineMIS.ORM.DAO.headQ.inventoryFlow.HeadQInventoryStoreDAOImpl;
import com.onlineMIS.ORM.DAO.headQ.supplier.finance.SupplierAcctFlowDaoImpl;
import com.onlineMIS.ORM.DAO.headQ.supplier.supplierMgmt.HeadQSupplierDaoImpl;
import com.onlineMIS.ORM.DAO.headQ.user.UserInforDaoImpl;
import com.onlineMIS.ORM.entity.headQ.barcodeGentor.Brand;
import com.onlineMIS.ORM.entity.headQ.barcodeGentor.Category;
import com.onlineMIS.ORM.entity.headQ.barcodeGentor.Color;
import com.onlineMIS.ORM.entity.headQ.barcodeGentor.NumPerHand;
import com.onlineMIS.ORM.entity.headQ.barcodeGentor.Product;
import com.onlineMIS.ORM.entity.headQ.barcodeGentor.ProductBarcode;
import com.onlineMIS.ORM.entity.headQ.barcodeGentor.ProductUnit;
import com.onlineMIS.ORM.entity.headQ.barcodeGentor.Year;
import com.onlineMIS.ORM.entity.headQ.inventory.HeadQSalesHistory;
import com.onlineMIS.ORM.entity.headQ.inventory.HeadQSalesHistoryId;
import com.onlineMIS.ORM.entity.headQ.inventory.InventoryOrder;
import com.onlineMIS.ORM.entity.headQ.inventory.InventoryOrderProduct;
import com.onlineMIS.ORM.entity.headQ.inventory.InventoryOrderTemplate;
import com.onlineMIS.ORM.entity.headQ.inventory.InventoryOrderVO;
import com.onlineMIS.ORM.entity.headQ.inventory.JinSuanOrderTemplate;
import com.onlineMIS.ORM.entity.headQ.inventoryFlow.HeadQInventoryStock;
import com.onlineMIS.ORM.entity.headQ.inventoryFlow.HeadQInventoryStore;
import com.onlineMIS.ORM.entity.headQ.supplier.finance.SupplierAcctFlow;
import com.onlineMIS.ORM.entity.headQ.supplier.purchase.HeadqPurchaseHistory;
import com.onlineMIS.ORM.entity.headQ.supplier.purchase.PurchaseOrder;
import com.onlineMIS.ORM.entity.headQ.supplier.purchase.PurchaseOrderPrintVO;
import com.onlineMIS.ORM.entity.headQ.supplier.purchase.PurchaseOrderProduct;
import com.onlineMIS.ORM.entity.headQ.supplier.purchase.PurchaseOrderVO;
import com.onlineMIS.ORM.entity.headQ.supplier.purchase.SupplierOrdersTemplate;
import com.onlineMIS.ORM.entity.headQ.supplier.purchase.SupplierPurchaseOrderTemplate;
import com.onlineMIS.ORM.entity.headQ.supplier.supplierMgmt.HeadQSupplier;
import com.onlineMIS.ORM.entity.headQ.user.UserInfor;
import com.onlineMIS.action.headQ.supplier.purchase.SupplierPurchaseActionFormBean;
import com.onlineMIS.action.headQ.supplier.purchase.SupplierPurchaseActionUIBean;
import com.onlineMIS.common.Common_util;
import com.onlineMIS.common.ExcelUtil;
import com.onlineMIS.common.loggerLocal;
import com.onlineMIS.filter.SystemParm;


@Service
public class SupplierPurchaseService {
	@Autowired
	private HeadQInventoryStockDAOImpl headQInventoryStockDAOImpl;
	@Autowired
	private com.onlineMIS.ORM.DAO.headQ.barCodeGentor.BrandDaoImpl brandDaoImpl;
	@Autowired
	private ProductsMSDAOImpl productsMSImpl;
	@Autowired
	private BilldraftidxDAOImpl billdraftidxImpl;
	@Autowired
	private com.onlineMIS.ORM.DAO.headQ.barCodeGentor.CategoryDaoImpl categoryDaoImpl;

	@Autowired
	private StoremanagebilldrfDAOImpl StoremanagebilldrfDAOImpl;
	@Autowired
	private com.onlineMIS.ORM.DAO.headQ.barCodeGentor.ColorDaoImpl colorDaoImpl;

	@Autowired
	private BuymanagebilldrfDAOImpl buymanagebilldrfDAOImpl;

	@Autowired
	private com.onlineMIS.ORM.DAO.headQ.barCodeGentor.NumPerHandDaoImpl numPerHandDaoImpl;
	
	@Autowired
	private PurchaseOrderDaoImpl purchaseOrderDaoImpl;
	@Autowired
	private PurchaseOrderProductDaoImpl PurchaseOrderProductDaoImpl;
	@Autowired
	private ProductBarcodeDaoImpl ProductBarcodeDaoImpl;
	@Autowired
	private ProductDaoImpl ProductDaoImpl;
	@Autowired
	private HeadQSupplierDaoImpl headQSupplierDaoImpl;
	@Autowired
	private SupplierAcctFlowDaoImpl supplierAcctFlowDaoImpl;
	@Autowired
	private InventoryService inventoryService;
	@Autowired
	private UserInforDaoImpl userInforDaoImpl;
	
	@Autowired
	private HeadqPurchaseHistoryDaoImpl headqPurchaseHistoryDaoImpl;
	@Autowired
	private com.onlineMIS.ORM.DAO.headQ.barCodeGentor.ProductDaoImpl productDaoImpl;

	@Autowired
	private com.onlineMIS.ORM.DAO.headQ.barCodeGentor.ProductBarcodeDaoImpl productBarcodeDaoImpl;

	@Autowired
	private HeadQInventoryStoreDAOImpl headQInventoryStoreDAOImpl;
	
	/**
	 * 获取单据信息
	 * Action 1: edit; 2 : view
	 * @param id
	 * @param loginUser
	 * @return
	 */
	@Transactional
	public Response loadPurchaseOrder(int id, UserInfor loginUser){
		Response response = new Response();
		
		PurchaseOrder order = purchaseOrderDaoImpl.get(id, true);
		if (order == null){
			response.setFail("无法找到 采购单据 : " + id);
		} else {
			int status = order.getStatus();
			
			switch (status) {
				case PurchaseOrder.STATUS_DRAFT:
					purchaseOrderDaoImpl.initialize(order);
						order.putSetToList();
						
						response.setReturnValue(order);
						response.setAction(1);
					break;
				case PurchaseOrder.STATUS_CANCEL:
				case PurchaseOrder.STATUS_COMPLETE:
					purchaseOrderDaoImpl.initialize(order);
					order.putSetToList();
					
					response.setReturnValue(order);
					response.setAction(2);
				    break;	
				case PurchaseOrder.STATUS_DELETED:
					response.setFail("采购单据 : " + id + " 已经被删除.");
					break;
			    default:
			    	response.setFail("采购单据状态错误 : " + id);
				    break;
			}

		}
		
		return response;
	}
	
	/**
	 * 删除单据
	 * @param id
	 * @param loginUser
	 * @return
	 */
	@Transactional
	public Response deletePurchaseOrderById(int id, UserInfor loginUser){
		Response response = new Response();
		
		if (id == 0){
			response.setFail("采购单据尚未保存，无法删除 .");
		} else {
			PurchaseOrder order = purchaseOrderDaoImpl.get(id, true);
			try {
				UserInfor orderOwner = order.getOrderAuditor();
				if (orderOwner.getUser_id() != loginUser.getUser_id()){
					response.setFail("你没有权限删除 采购单据  : "+orderOwner.getUser_name());
				} else {
					order.setLastUpdateTime(Common_util.getToday());
					order.setStatus(PurchaseOrder.STATUS_DELETED);
					purchaseOrderDaoImpl.update(order, true);
				}
			} catch (Exception e){
				response.setFail(e.getMessage());
			}
		}
		
		return response;
	}
	
	/**
	 * @tobecheck
	 * 保存purchase order
	 * @param order
	 * @param loginUser
	 * @return
	 */
	@Transactional
	public Response savePurchaseOrderToDraft(PurchaseOrder order, UserInfor loginUser){

		Response response = new Response();

		try {

			response = validatePurchaseOrder(order);
			if (!response.isSuccess()){
				return response;
			}
			
			response = recalculatePurchaseOrder(order);
			if (!response.isSuccess())
				return response;
	
			if (order.getId() == 0){
				order.setCreationTime(Common_util.getToday());
				order.setLastUpdateTime(Common_util.getToday());
				order.setOrderAuditor(loginUser);
				order.setStatus(PurchaseOrder.STATUS_DRAFT);
				order.putListToSet();
				
				purchaseOrderDaoImpl.save(order, true);
			} else {
				PurchaseOrder orderOriginal = purchaseOrderDaoImpl.get(order.getId(), true);

				PurchaseOrderProductDaoImpl.removeItems(order.getId());
				
				orderOriginal.copyFrom(order);
				
				orderOriginal.setLastUpdateTime(Common_util.getToday());
				orderOriginal.setOrderAuditor(loginUser);
				orderOriginal.setStatus(PurchaseOrder.STATUS_DRAFT);
	
				order.putListToSet();	
				orderOriginal.setProductSet(order.getProductSet());
				
				purchaseOrderDaoImpl.update(orderOriginal, true);
			}
		} catch (Exception exception){
			exception.printStackTrace();
			response.setFail(exception.getMessage());
		}
		
		return response;
	}
	

	/**
	 * @tobecheck
	 * 保存purchase order过账
	 * @param order
	 * @param loginUser
	 * @return
	 * @throws Exception 
	 */
	@Transactional
	public Response savePurchaseOrderToComplete(PurchaseOrder order, UserInfor loginUser) throws Exception{
		Response response = new Response();
		
		try {
			response = validatePurchaseOrder(order);
			if (!response.isSuccess()) {
				return response;
			}

			response = recalculatePurchaseOrder(order);
			if (!response.isSuccess())
				return response;

			// 1. 保存单据

			if (order.getId() == 0) {
				order.setLastUpdateTime(Common_util.getToday());
				order.setOrderAuditor(loginUser);
				order.setStatus(PurchaseOrder.STATUS_COMPLETE);
				order.putListToSet();

				purchaseOrderDaoImpl.save(order, true);

				// 2. 过账账目
				updateSupplierAcctFlow(order, false);

				// 3. 计算库存
				updateHeadqInventory(order, false);

				// 4.更新最新成本
				updateRecCost(order);

				response = procureResult(order.getType(), BaseOrder.STATUS_COMPLETE);
			} else {
				PurchaseOrderProductDaoImpl.removeItems(order.getId());
				PurchaseOrder orderOriginal = purchaseOrderDaoImpl.get(order.getId(), true);

				orderOriginal.copyFrom(order);

				orderOriginal.setLastUpdateTime(Common_util.getToday());
				orderOriginal.setOrderAuditor(loginUser);
				orderOriginal.setStatus(PurchaseOrder.STATUS_COMPLETE);

				order.putListToSet();
				orderOriginal.setProductSet(order.getProductSet());

				purchaseOrderDaoImpl.update(orderOriginal, true);

				// 2. 过账账目
				updateSupplierAcctFlow(orderOriginal, false);

				// 3. 计算库存
				updateHeadqInventory(orderOriginal, false);

				// 4.更新最新成本
				updateRecCost(orderOriginal);

				response = procureResult(order.getType(), BaseOrder.STATUS_DRAFT);
			}

		} catch (Exception exception) {
			exception.printStackTrace();
			response.setFail(exception.getMessage());
		}

		return response;
	}
	
	
	private Response procureResult(int procureType,int status) {
		Response response = new Response();
		switch (procureType) {
		case PurchaseOrder.TYPE_PURCHASE:
			response.setReturnValue(PurchaseOrder.TYPE_PURCHASE);
			if (status == BaseOrder.STATUS_COMPLETE) {
				response.setSuccess("采购单据录入成功！");
			}else {
				response.setSuccess("采购草稿录入成功！");
			}			
			break;
		case PurchaseOrder.TYPE_RETURN:
			response.setReturnValue(PurchaseOrder.TYPE_PURCHASE);
			if (status == BaseOrder.STATUS_COMPLETE) {
				response.setSuccess("采购退货单据录入成功！");
			}else {
				response.setSuccess("采购退货草稿录入成功！");
			}			
			break;
		case PurchaseOrder.TYPE_FREE:
			response.setReturnValue(PurchaseOrder.TYPE_PURCHASE);
			if (status == BaseOrder.STATUS_COMPLETE) {
				response.setSuccess("采购赠送单据录入成功！");
			}else {
				response.setSuccess("采购赠送草稿录入成功！");
			}			
			break;
		default:
			break;
		}	
		return response;
		
	}
	
	
	/**
	 * 更新最新的成本到基础资料
	 * @param order
	 */
	private void updateRecCost(PurchaseOrder order) {
		//如果是测试连锁店不需要
		/**
		 * 
                不修改价格
		int TEST_SUPPLIER_ID = SystemParm.getTestSupplierId();
		int supplierId = order.getSupplier().getId();
		if (supplierId == TEST_SUPPLIER_ID)
			return;
		
		Iterator<PurchaseOrderProduct> orderProducts = order.getProductSet().iterator();
		 while (orderProducts.hasNext()){
			 PurchaseOrderProduct orderProduct = orderProducts.next();
			 int pbId = orderProduct.getPb().getId();
			 double cost = orderProduct.getRecCost();

			 ProductBarcode pb = ProductBarcodeDaoImpl.get(pbId, true);
			 
			 Product product = pb.getProduct();
			 product.setRecCost(cost);
			 
			 ProductDaoImpl.save(product, true);
		 }
		  */
	}

	/**
	 * @tobecheck
	 * 红虫purchase order过账
	 * @param order
	 * @param loginUser
	 * @return
	 */
	@Transactional
	public Response cancelPurchaseOrder(int orderId, UserInfor loginUser){
		Response response = new Response();
				
		//1. 保存单据
		PurchaseOrder orderOriginal = purchaseOrderDaoImpl.get(orderId, true);
		if (orderOriginal == null){
			response.setFail("单据还未过账无法红冲");
		} else {
			if (orderOriginal.getStatus() != PurchaseOrder.STATUS_COMPLETE){
				response.setFail("单据还未过账无法红冲");
			} else {
				//orderOriginal.setLastUpdateTime(Common_util.getToday());
				orderOriginal.setOrderAuditor(loginUser);
				orderOriginal.setStatus(PurchaseOrder.STATUS_CANCEL);
				orderOriginal.putListToSet();
				
				purchaseOrderDaoImpl.save(orderOriginal, true);
			}
		}
		
		//2. 过账账目
		updateSupplierAcctFlow(orderOriginal, true);
				
		//3. 计算库存
		updateHeadqInventory(orderOriginal, true);
		
		return response;
	}
	
	/**
	 * 更新库存信息, 以及历史购买记录
	 * @param order
	 * @param b
	 */
	public void updateHeadqInventory(PurchaseOrder order, boolean isCancel) {
		//如果是测试连锁店不需要
		int TEST_SUPPLIER_ID = SystemParm.getTestSupplierId();
		int supplierId = order.getSupplier().getId();
		if (supplierId == TEST_SUPPLIER_ID)
			return;
		
		int orderId = order.getId();
		String inventoryStockId = "";
		
		//更新库存数据
		HeadQInventoryStore store = order.getStore();
		int storeId = store.getId();
		
		int offset = 1;
		if (isCancel){
			offset = -1;
			inventoryStockId = "C";
		} 

		if (order.getType() == PurchaseOrder.TYPE_RETURN  ){ //采购退货
			offset *= -1;	
			inventoryStockId += HeadQInventoryStock.SUPPLIER_RETURN + orderId;
		} else if(order.getType() == PurchaseOrder.TYPE_PURCHASE) { //采购录入
			inventoryStockId += HeadQInventoryStock.SUPPLIER_PURCHASE + orderId;
		} else if(order.getType() == PurchaseOrder.TYPE_FREE) {//采购赠送
			inventoryStockId += HeadQInventoryStock.SUPPLIER_FREE + orderId;
		}
		
		Iterator<PurchaseOrderProduct> orderProducts = order.getProductSet().iterator();
		 while (orderProducts.hasNext()){
			 PurchaseOrderProduct orderProduct = orderProducts.next();
			 int pbId = orderProduct.getPb().getId();
			 double cost = orderProduct.getRecCost();
			 double wholeSalePrice = orderProduct.getWholeSalePrice();
			 int quantity = orderProduct.getQuantity() * offset;
			 double costTotal = cost * quantity;
			 double wholeSalesTotal = wholeSalePrice * quantity;
			 double discount = orderProduct.getDiscount();
			 ProductBarcode pb = ProductBarcodeDaoImpl.get(pbId, true);
			 //注意：采购单据这里取的是createTime字段
			 HeadQInventoryStock stock = new HeadQInventoryStock(storeId, pb, inventoryStockId, quantity, cost,  wholeSalePrice,costTotal, wholeSalesTotal,discount,order.getCreationTime());
			 //HeadQInventoryStock stock = new HeadQInventoryStock(storeId, inventoryStockId, cost, costTotal, wholeSalePrice, wholeSalesTotal, quantity, pb);
			 
			 
			 headQInventoryStockDAOImpl.save(stock, true);
			 

			 HeadqPurchaseHistory purchaseHistory = new HeadqPurchaseHistory(pbId, cost, wholeSalePrice, quantity);
			 headqPurchaseHistoryDaoImpl.saveOrUpdate(purchaseHistory, true);

		 }
	}

	/**
	 * to update the chain's acct flow
	 * @param order
	 * @param b
	 */
    private void updateSupplierAcctFlow(PurchaseOrder order,  boolean isCancel) {
    	int supplierId = order.getSupplier().getId();
		
    	HeadQSupplier supplier = headQSupplierDaoImpl.get(supplierId, true);
    	
		int orderId = order.getId();
    	
    	int orderType = order.getType();
    	double totalAmt = order.getTotalRecCost();
    	double totalDis = order.getTotalDiscount();
    	double netAmt = totalAmt - totalDis;
    	
    	//1. update the offset
    	int offset = 1;
		if (orderType == PurchaseOrder.TYPE_RETURN)
			offset *= -1;
		else if (orderType == PurchaseOrder.TYPE_FREE)
		    offset = 0;
			
		if (isCancel)
			offset *= -1;
    	
		netAmt *= offset;
		
		//2.update the order's preAcctAmt and postAcctAmt
		double initialAcctAmt = supplier.getInitialAcctBalance();  		
		double acctAmtFlow = supplierAcctFlowDaoImpl.getAccumulateAcctFlow(supplierId);
		double preAcctAmt = Common_util.getDecimalDouble(initialAcctAmt + acctAmtFlow);
		double postAcctAmt = Common_util.getDecimalDouble(preAcctAmt + netAmt);
		if (!isCancel){  
			String hql = "update PurchaseOrder set preAcctAmt =?, postAcctAmt=? where id=?";
			Object[] values = {preAcctAmt, postAcctAmt, orderId};
			
			purchaseOrderDaoImpl.executeHQLUpdateDelete(hql, values, false);
		}
		
		supplier.setCurrentAcctBalance(postAcctAmt);
		headQSupplierDaoImpl.update(supplier, true);
		
		SupplierAcctFlow supplierAcctFlow = new SupplierAcctFlow(supplierId, netAmt, "S," + orderId + "," + isCancel, order.getLastUpdateTime());
		supplierAcctFlowDaoImpl.save(supplierAcctFlow, true);
	
	}
    
	/**
	 * 再次汇总
	 * 合并重复的产品
	 * @param order
	 * @throws Exception 
	 */
	private Response recalculatePurchaseOrder(PurchaseOrder order)  {
		Response response = new Response();
		
		/**
		 * this is the barcode list with a sequence
		 */
		Map<Integer, PurchaseOrderProduct> orderProductMap = new HashMap<Integer, PurchaseOrderProduct>();
		
		List<PurchaseOrderProduct> orderProducts = order.getProductList();
		Set<Integer> pbIds = new LinkedHashSet<Integer>();

		
		/**
		 * 1. to group the products' quantity, recost, whole sales and build the index
		 */

        
		for (PurchaseOrderProduct orderProduct: orderProducts){
			if (orderProduct!= null && orderProduct.getPb() != null && orderProduct.getPb().getId() != 0){
				int pbId = orderProduct.getPb().getId();
				

//				orderProduct.setPb(pBarcode);
				
				if (orderProductMap.containsKey(pbId)){
					PurchaseOrderProduct original_orderProduct = orderProductMap.get(pbId);
					int addQuantity = orderProduct.getQuantity();
					int orignalQuantity = original_orderProduct.getQuantity();
					original_orderProduct.setQuantity(addQuantity + orignalQuantity);
					
				} else {
					orderProductMap.put(pbId, orderProduct);
				}

				
				pbIds.add(pbId);
			}
		}

		List<PurchaseOrderProduct> orderProducts2 = new ArrayList<PurchaseOrderProduct>();
		order.getProductList().clear();
		
		int i = 0;
        double totalRecCost = 0;
        double totalWholePrice = 0;
        double totalRecCostRow = 0;
        double totalWholePriceRow = 0;
        int totalQuantity = 0;
		for (Integer pbId2 : pbIds){
			PurchaseOrderProduct orderProduct = orderProductMap.get(pbId2);
			if (orderProduct == null){
				response.setFail("合并货品出现错误");
				return response;
			} else {
				int pbId = orderProduct.getPb().getId();
				ProductBarcode pBarcode = ProductBarcodeDaoImpl.get(pbId, true);
				//总部获取的预计批发价
				double wholePrice = ProductBarcodeDaoImpl.getWholeSalePrice(pBarcode);
				//总部获取的产品标准成本
		        //double standardCost = pBarcode.getProduct().getRecCost();
//				double standardCost = orderProduct.getPrice();
				orderProduct.setWholeSalePrice(wholePrice);

//				orderProduct.setDiscount(Common_util.roundDouble(orderProduct.getRecCost()/standardCost, 2));
				
				
				totalRecCostRow = orderProduct.getRecCost() * orderProduct.getQuantity();
				totalWholePriceRow = orderProduct.getWholeSalePrice() * orderProduct.getQuantity();
				
				orderProduct.setTotalRecCost(totalRecCostRow);
				orderProduct.setTotalWholeSalePrice(totalWholePriceRow);
				
				totalQuantity += orderProduct.getQuantity();
				totalRecCost += totalRecCostRow;
				totalWholePrice += totalWholePriceRow;
				
				
				orderProduct.setIndex(i++);
				orderProducts2.add(orderProduct);
			}
		}
		
		if (Math.abs(totalRecCost - order.getTotalRecCost()) > 2) {
			response.setFail("页面数据的总成本 和 实际计算的总成本 差距太大,请重新计算后保存");
			return response;
		} 
		
		if (Math.abs(totalQuantity - order.getTotalQuantity()) > 0) {
			response.setFail("页面数据的总数量 和 实际计算的总数量 有差距,请重新计算后保存");
			return response;
		} 
		
		order.setTotalRecCost(totalRecCost);
		order.setTotalWholePrice(totalWholePrice);
		order.setTotalQuantity(totalQuantity);
		
		order.setProductList(orderProducts2);

		return response;
	}

	/**
	 * 验证单据的信息是否都正确
	 * @param order
	 * @return
	 */
	private Response validatePurchaseOrder(PurchaseOrder order){
		Response response = new Response();
		boolean success = true;
		
		List<PurchaseOrderProduct> productList = order.getProductList();
		String errorMsg = "";
		
		for (PurchaseOrderProduct orderProduct : productList){
			if (orderProduct != null && orderProduct.getPb()!=null) {
				int quantity = orderProduct.getQuantity();
				if (quantity <= 0){
					errorMsg += "条码 " + orderProduct.getPb().getBarcode() + " 的数量必须是>0\n";
					success = false;
				}
			}			
		}		
		if (!success){
			response.setFail(errorMsg);
		}
		
		//校验库房和货品是否统一
		errorMsg = isCheckQxOrXlc(order);
		if (errorMsg.length() > 0) {
			response.setFail(errorMsg);
			return response;
		}
		
		return response;
	}
	
	/**
	 * 验证客户，库房，产品是否为同一归属
	 * @param order
	 * @return
	 */
	private String isCheckQxOrXlc(PurchaseOrder order) {
		String errorMsg = "";
		// 库房
		HeadQInventoryStore store = headQInventoryStoreDAOImpl.get(order.getStore().getId(), true);

		if (order.getProductList().size() != 0) {
			for (PurchaseOrderProduct product : order.getProductList()) {
				if (product != null && product.getPb() != null) {
					ProductBarcode pb = productBarcodeDaoImpl.get(product.getPb().getId(), true);
					if (pb != null) {
						Brand brand = pb.getProduct().getBrand();
						if (brand != null && brand.getBelong_To() != store.getBelongTo()) {
							errorMsg = HeadQInventoryStore.belongToMap.get(store.getBelongTo()) + "库房：无法选择" + Brand.belongToMap.get(brand.getBelong_To()) + "货品，条码：" + pb.getBarcode();
						}
					}
				}
								
			}
		}
		return errorMsg;
	}

	/**
	 * 准备搜索的页面
	 * @param uiBean
	 */
	public void prepareSearchPurchasePage(SupplierPurchaseActionFormBean formBean) {
		formBean.getOrder().setType(Common_util.ALL_RECORD);

	}

	public void prepareEditPurchasePage(SupplierPurchaseActionUIBean uiBean) throws Exception {
        List<UserInfor> users  = userInforDaoImpl.getProcureUses();	
        List<UserInfor> newUsers = new ArrayList<UserInfor>();
        for (UserInfor user: users){
        	user.setName(user.getPinyin().substring(0, 1) + " " + user.getName());
        	newUsers.add(user);
        }
		
        List<HeadQInventoryStore> stores = new ArrayList<HeadQInventoryStore>();
        stores = headQInventoryStoreDAOImpl.getActiveStores();
        uiBean.setStores(stores);
        
		uiBean.setUsers(newUsers);
		
	}

	/**
	 * purchase order上面扫描条码
	 * @param barcode
	 * @param id
	 * @param type
	 * @return
	 */
	@Transactional
	public Response scanByBarcodePurchaseOrder(String barcode, int supplierId, int orderType, int indexPage, int fromSrc) {
		Response response = new Response();
		Map<String, Object> dataMap = new HashMap<String, Object>();
		
		ProductBarcode productBarcode = ProductBarcodeDaoImpl.getByBarcode(barcode);
		
		if (productBarcode!= null && (productBarcode.getStatus() == ProductBarcode.STATUS_OK || productBarcode.getStatus() == ProductBarcode.STATUS_NOT_PRODUCE)){
				PurchaseOrderProduct pop = new PurchaseOrderProduct();
				pop.setPb(productBarcode);
				
				Product product = productBarcode.getProduct();
				int productId = productBarcode.getId();
			    HeadqPurchaseHistory salesHistory = headqPurchaseHistoryDaoImpl.get(productId, true);
			
                if (orderType == PurchaseOrder.TYPE_PURCHASE || orderType == PurchaseOrder.TYPE_RETURN){
					pop.setWholeSalePrice(ProductBarcodeDaoImpl.getWholeSalePrice(productBarcode));
        			if (salesHistory != null){
        				pop.setRecCost(salesHistory.getRecCost());
        			} else {
        				pop.setRecCost(productBarcode.getProduct().getRecCost());
        			}
        			pop.setTotalRecCost(pop.getRecCost()*product.getNumPerHand());
        			pop.setQuantity(product.getNumPerHand());
        			pop.setDiscount(pop.getRecCost() / product.getRecCost());
					dataMap.put("pop", pop);
					dataMap.put("orderType", orderType);
					dataMap.put("index", indexPage);
					dataMap.put("where", fromSrc);
					
					response.setReturnValue(dataMap);
                } else if (orderType == PurchaseOrder.TYPE_FREE){
                	pop.setWholeSalePrice(ProductBarcodeDaoImpl.getWholeSalePrice(productBarcode));
        			if (salesHistory != null){
        				pop.setRecCost(salesHistory.getRecCost());
        				//product.setWholeSalePrice(salesHistory.getWholePrice());

        			} else {
        				pop.setRecCost(0);
        				//product.setWholeSalePrice(0);
        			}
        			pop.setTotalRecCost(pop.getRecCost()*product.getNumPerHand());
        			pop.setQuantity(product.getNumPerHand());
        			pop.setDiscount(pop.getRecCost() / product.getRecCost());
					dataMap.put("pop", pop);
					dataMap.put("orderType", orderType);
					dataMap.put("index", indexPage);
					dataMap.put("where", fromSrc);
					
					
                } else 
                	response.setFail("无法找到条码数据");
	    } else {
	    	response.setFail("无法找到条码数据");
	    }

		response.setReturnValue(dataMap);
		
		return response;
	}

	/**
	 * 通过页面搜索采购单据
	 * @param formBean
	 * @return
	 */
	public Response searchPurchaseOrder(SupplierPurchaseActionFormBean formBean) {
		Response response = new Response();
	    DetachedCriteria criteria = DetachedCriteria.forClass(PurchaseOrder.class,"order");
		
		PurchaseOrder searchBean = formBean.getOrder();
		List<PurchaseOrderVO> orderVOs = new ArrayList<PurchaseOrderVO>();
		
		List<PurchaseOrderVO> footers = new ArrayList<PurchaseOrderVO>();
		PurchaseOrderVO footer = new PurchaseOrderVO();

			if (searchBean.getOrderId() != null){
				criteria.add(Restrictions.eq("order.id", searchBean.getOrderId()));
				
				criteria.add(Restrictions.ne("order.status", PurchaseOrder.STATUS_DELETED));
			} else {
				Date startTime = formBean.getSearchStartTime();
				Date endTime = formBean.getSearchEndTime();
		
				if (searchBean.getStatus() != Common_util.ALL_RECORD)
					criteria.add(Restrictions.eq("order.status", searchBean.getStatus()));
				else
					criteria.add(Restrictions.ne("order.status", PurchaseOrder.STATUS_DELETED));
				
				if (searchBean.getSupplier().getId() != 0 && !searchBean.getSupplier().getName().equals("")){
					int supplierId = searchBean.getSupplier().getId();
		
					criteria.add(Restrictions.eq("order.supplier.id", supplierId));
				}
				
				if (formBean.getBelongTo() != Common_util.ALL_RECORD) {
					List<HeadQInventoryStore> stores = headQInventoryStoreDAOImpl.getStoresByBelongTo(formBean.getBelongTo());
					Set<Integer> storeIdSet = new HashSet<Integer>();
					for(HeadQInventoryStore store : stores)
						storeIdSet.add(store.getId());
					
					criteria.add(Restrictions.in("store.id", storeIdSet));
				}
				
				String comment = formBean.getOrder().getComment().trim();
				if (!comment.equals("")){
					criteria.add(Restrictions.like("order.comment", comment, MatchMode.ANYWHERE));
				}
	
				if (startTime != null && endTime != null){
					Date end_date = Common_util.formEndDate(endTime);
					criteria.add(Restrictions.between("order.creationTime",startTime,end_date));
				}
				
				if (searchBean.getType() != Common_util.ALL_RECORD)
					criteria.add(Restrictions.eq("order.type",searchBean.getType()));
				
				if (!StringUtils.isEmpty(formBean.getPbIds())){
					String[] productIds = formBean.getPbIds().split(",");
					if (productIds.length > 0){
						Set<Integer> productIdSet = new HashSet<Integer>();
						for (String id : productIds){
							productIdSet.add(Integer.parseInt(id));
						}
						DetachedCriteria inventoryProduct = criteria.createCriteria("productSet");
						inventoryProduct.add(Restrictions.in("pb.id", productIdSet));
						
					}
				}
				
				criteria.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY);
				criteria.addOrder(Order.asc("order.creationTime"));
			}
			List<PurchaseOrder> orders = purchaseOrderDaoImpl.getByCritera(criteria, true);
				
			if (!orders.isEmpty()) {
				int totalQ = 0;
				double totalCost = 0;
				double totalWholeSales = 0;
				int exportJinsuan = 0;
				for (PurchaseOrder order : orders){
					PurchaseOrderVO purchaseOrderVO = new PurchaseOrderVO(order);
					orderVOs.add(purchaseOrderVO);
					
					exportJinsuan += order.getExportNum();
					
					int orderType = order.getType();
						switch (orderType) {
							case PurchaseOrder.TYPE_PURCHASE:
								totalQ += order.getTotalQuantity();
								totalCost += order.getTotalRecCost();
								totalWholeSales += order.getTotalWholePrice();
								break;
							case PurchaseOrder.TYPE_RETURN:
								totalQ -= order.getTotalQuantity();
								totalCost -= order.getTotalRecCost();
								totalWholeSales -= order.getTotalWholePrice();
								break;
							default:
								break;
						}
				}
				
				footer.setTotalQuantity(totalQ);
				footer.setTotalWholePrice(totalWholeSales);
				footer.setTotalRecCost(totalCost);
				footer.setSupplier("合计");
				footer.setExportNum(exportJinsuan);
			}
		
		Map<String, Object> data = new HashMap<String, Object>();
		data.put("rows", orderVOs);
		

		footers.add(footer);
		data.put("footer", footers);
		
		response.setReturnValue(data);
		
		return response;
	}

	/**
	 * 获取单据准备打印
	 * @param orderId
	 * @return
	 */
	@Transactional
	public Response getPurchaseOrderForPrint(int orderId) {
		Response response = new Response();
		
		PurchaseOrder order = purchaseOrderDaoImpl.get(orderId, true);
		if (order == null){
			response.setFail("单据无法找到");
		} else {
			order.putSetToList();
			
			PurchaseOrderPrintVO printVO = new PurchaseOrderPrintVO(order);
			response.setReturnValue(printVO);
		}
		
		return response;
	}
	
	/**
	 * 复制purchase order
	 * @param order
	 * @return
	 */
	@Transactional
	public Response copyPurchaseOrder(PurchaseOrder order, UserInfor orderAuditor){
		Response response = new Response();
		int orderId = order.getId();
		
		if (orderId > 0){
			PurchaseOrder orderInDB = purchaseOrderDaoImpl.get(orderId, true);
			purchaseOrderDaoImpl.initialize(orderInDB);
			purchaseOrderDaoImpl.evict(orderInDB);
			
			order = orderInDB;
			order.setId(0);
			
            String comment = order.getComment();
            
            order.setComment(comment + "\n 复制于单据" + orderId);
			order.setLastUpdateTime(Common_util.getToday());
			order.setOrderAuditor(orderAuditor);
			order.setCreationTime(Common_util.getToday());
			order.setStatus(PurchaseOrder.STATUS_DRAFT);
			order.setExportNum(0);
			
			purchaseOrderDaoImpl.save(order, true);

			response.setReturnCode(Response.SUCCESS);
			response.setReturnValue(order.getId());
		} else 
			response.setReturnCode(Response.FAIL);
		
		return response;
	}
	
	/**
	 * 更新order 的 comment
	 * @param order
	 * @return
	 */
	public Response updateOrderComment(PurchaseOrder order) {
	       Response response = new Response();
			
	       if (order!= null && order.getId() != 0){
				String hql_order = "UPDATE PurchaseOrder i set i.comment = ? where id = ?";
				Object[] values = {order.getComment(),order.getId()};
				try {
					purchaseOrderDaoImpl.executeHQLUpdateDelete(hql_order, values, true);
				   response.setSuccess("成功更新备注");
				} catch (Exception e){
				   response.setFail(e.getMessage());
				}
				
	        } else {
	        	response.setQuickValue(Response.FAIL, "无法找到当前订单号");
	        }
	        
	        return response;
	}
	
	
	/**
	 * 复制Purchase order到批发销售
	 * @param order
	 * @param loginUserInfor
	 * @param priceMode = 1 : 按照批发价导出
	 * 		  priceMode = 2 : 按照采购价导出
	 * @return
	 */
	@Transactional
	public Response copyPurchaseOrder2WholeSales(PurchaseOrder order,
			UserInfor orderAuditor, int priceMode) {

		Response response = new Response();
		int orderId = order.getId();
		
		if (orderId > 0){
			PurchaseOrder orderInDB = purchaseOrderDaoImpl.get(orderId, true);
			
			//采购入库单的导入
			if (orderInDB.getType() == PurchaseOrder.TYPE_PURCHASE){
				
				if (orderInDB.getStatus() != PurchaseOrder.STATUS_COMPLETE){
					response.setFail("只能导出完成状态的采购单据");
					return response;
				}
				
				try {
					purchaseOrderDaoImpl.initialize(orderInDB);
					orderInDB.putSetToList();
					
					InventoryOrder wOrder = new InventoryOrder();
					wOrder.setComment("导入 " + orderInDB.getComment());
					wOrder.setOrder_Keeper(orderAuditor);
					wOrder.setOrder_StartTime(order.getLastUpdateTime());
					wOrder.setOrder_Status(InventoryOrder.STATUS_DRAFT);
					//wOrder.setCust(null);
					wOrder.setOrder_type(InventoryOrder.TYPE_SALES_ORDER_W);
					
					List<PurchaseOrderProduct> pListp = orderInDB.getProductList();
					List<InventoryOrderProduct> iListp = new ArrayList<InventoryOrderProduct>();
					for (PurchaseOrderProduct pop : pListp){
						InventoryOrderProduct iop = new InventoryOrderProduct();
						
						ProductBarcode pb = pop.getPb();
						iop.setProductBarcode(pb);
						
						int index = pop.getIndex();
						iop.setIndex(index);
						
						iop.setQuantity(pop.getQuantity());
						
						double selectPrice = 0;
						double wholePrice = 0;
						double discount = 1;
						if (priceMode ==1 ){
							selectPrice = ProductBarcodeDaoImpl.getSelectedSalePrice(pb);
							wholePrice = ProductBarcodeDaoImpl.getWholeSalePrice(pb);
							discount = 1;
							if (selectPrice == pb.getProduct().getSalesPriceFactory()){
								discount = pb.getProduct().getDiscount();
							}
						} else if (priceMode == 2){
							//如果这张采购单的选择价为空，就需要根据默认选择价计算
							if (pop.getPrice() == 0){
							    selectPrice = ProductBarcodeDaoImpl.getSelectedSalePrice(pb);
								discount = wholePrice/selectPrice;
								BigDecimal b = new BigDecimal(discount);  
								discount = b.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
							} else {
								//不为空，就直接用采购单的价格
								selectPrice = pop.getPrice();
								discount = pop.getDiscount();
							}
								
							wholePrice = pop.getRecCost();
						}
						iop.setDiscount(discount);
						iop.setSalePriceSelected(selectPrice);
						iop.setWholeSalePrice(wholePrice);
						
						iop.setOrder(wOrder);
						
						iListp.add(iop);
					}
					
					wOrder.setProduct_List(iListp);
					wOrder.putListToSet();
					
					response = inventoryService.saveToDraft(wOrder, "false",orderAuditor);
					if (!response.isSuccess())
						return response;
					
					int exportNum = orderInDB.getExportNum();
					exportNum++;
					String hql = "UPDATE PurchaseOrder set exportNum = " + exportNum + " WHERE id = " +orderId;
					purchaseOrderDaoImpl.executeHQLUpdateDelete(hql, null, true);
		
					response.setReturnCode(Response.SUCCESS);
					response.setReturnValue(order.getId());
				} catch (Exception e){
					loggerLocal.error("导出采购单据到批发销售出现问题 : " + orderId);
					loggerLocal.error(e);
					
					response.setFail("导出单据发生错误 : " + orderId + " , " + e.getMessage());
				}
			} else 
				response.setQuickValue(Response.WARNING, "该功能暂时只支持采购入库单的导出到批发销售端");
		} else 
			response.setQuickValue(Response.FAIL,"采购单据无法找到");
		
		return response;
	}

	   /**
  * 将精算excel单据转换成 purchase order 对象
  * @param orderExcel
  * @return
  * @throws IOException 
  */
	public PurchaseOrder transferJinSuanToObject(File orderExcel) throws IOException {
		JinSuanOrderTemplate jinSuanOrderTemplate = new JinSuanOrderTemplate(orderExcel);
		
		PurchaseOrder order = jinSuanOrderTemplate.transferExcelToPurchaseOrder();
		
		Set<String> barcodes = new HashSet<String>();
		List<PurchaseOrderProduct> orderProducts = order.getProductList();
		
		//to get the barcodes and transfer to objects
		for (PurchaseOrderProduct orderProduct: orderProducts)
			barcodes.add(orderProduct.getPb().getBarcode());

		List<ProductBarcode> ProductBarcodes = ProductBarcodeDaoImpl.getProductBarcodes(barcodes);
		HashMap<String, ProductBarcode> proHashMap = new HashMap<String, ProductBarcode>();
		
		for (ProductBarcode product: ProductBarcodes){
			proHashMap.put(product.getBarcode(), product);
		}
		
		//to set the product record
		for (PurchaseOrderProduct orderProduct: orderProducts){

    			
			String barcode  = orderProduct.getPb().getBarcode();
			ProductBarcode productBarcode = proHashMap.get(barcode);
			
			if (productBarcode != null){
            // Product product = productBarcode.getProduct();
             double wp = ProductBarcodeDaoImpl.getWholeSalePrice(productBarcode);

 			orderProduct.setWholeSalePrice(wp);

//		    int productId = productBarcode.getId();
//		    HeadqPurchaseHistory salesHistory = headqPurchaseHistoryDaoImpl.get(productId, true);
//	
//    		if (salesHistory != null){
//    			productBarcode.getProduct().setRecCost2(salesHistory.getRecCost());
//    		} else {
//    			productBarcode.getProduct().setRecCost2(productBarcode.getProduct().getRecCost());
//    		}
 			
			 orderProduct.setPb(productBarcode);
				//orderProduct.setRecCost(ProductBarcodeDaoImpl.getRecCost(productBarcode));
//	            orderProduct.setSalesPrice(product.getSalesPrice());
	            
	            //check whether the whole price is changed manually
//	            calculateSalePriceDiscount(orderProduct, product);
			} else {
				orderProduct.setWholeSalePrice(0);
				orderProduct.setRecCost(0);
			}
		}
		
		return order;
	}

	/**
	 * 将单据导入到精算
	 * @param order
	 * @param loginUserInfor
	 * @return
	 */
	@Transactional
	public Response saveToJinsuan(PurchaseOrder order2, UserInfor userInfor) {
		Response response = new Response();
		int orderId = order2.getId();
		loggerLocal.info("<---SupplierPurchaseService.saveToJinSuan() : order ID" + orderId);
		
		PurchaseOrder order = purchaseOrderDaoImpl.get(orderId, true);
		if (order == null) {
			response.setFail("无法找到单据 : " + orderId);
			return response;
		} else if (order.getStatus() != PurchaseOrder.STATUS_COMPLETE) {
			response.setFail("单据状态(" + order.getStatusS() +"), 无法导入精算");
			return response;
		} else if (order.getExportNum() > 0) {
			response.setFail("此单据导入精算次数(" + order.getExportNum() +"), 无法再次导入精算");
			return response;			
		}
		
		/**
		 * 第一步: 验证数据  is to validate the data
		 */
		String errorMessage = "";
		order.putSetToList();
		List<PurchaseOrderProduct> products = order.getProductList();

		// Put barcodes in the list
		Set<String> barcodes = new HashSet<String>();
		for (PurchaseOrderProduct product : products) {
			barcodes.add(product.getPb().getBarcode());
		}

		// get the serial numbers
		List<ProductBarcode> productBarcodes = productBarcodeDaoImpl.getProductBarcodes(barcodes);
		Set<String> serialNums = new HashSet<String>();
		for (ProductBarcode pb : productBarcodes) {
			serialNums.add(pb.getProduct().getSerialNum());
		}

		Map<String, ProductBarcode> productMap = productBarcodeDaoImpl.getProductMapByBarcode(barcodes);
		Map<String, ProductsMS> productMSMap = productsMSImpl.retrieveProducts(barcodes);
		for (String barcode : barcodes) {
			try {
				PriceMS priceMS = productMSMap.get(barcode).getPrice();
				ProductBarcode productBarcode = productMap.get(barcode);
				if (priceMS == null || productBarcode == null) {
					errorMessage += barcode + ",";
				}
			} catch (Exception e) {
				loggerLocal.error("PurchaseService.saveToJinSua()，barcode : " + barcode + " can't be found");
				errorMessage += barcode + ",";
			}
		}

		if (errorMessage.length() != 0)
			errorMessage = "以下条码不存在精算中 : " + errorMessage + "<br/>";

		int jinsuanID = userInfor.getJinsuanID();
		if (jinsuanID == 0) {
			errorMessage += "用户不存在精算账户，请联系系统管理员" + "<br/>";
		}
		
		if (errorMessage.length() == 0) {
			//重复计算totalQ和totalRow
			int totalQ = 0;
			int totalRow = 0;
			Billdraftidx billdraftidx = new Billdraftidx();
			billdraftidx.setBilldate(new Date());
			billdraftidx.setBillnumber("333-3333-333-333");
			if (order.getType() == PurchaseOrder.TYPE_PURCHASE)
				billdraftidx.setBilltype(Billdraftidx.PURCHASE);
			else if (order.getType() == PurchaseOrder.TYPE_RETURN)
				billdraftidx.setBilltype(Billdraftidx.PURCHASE_RETURN);
			else if (order.getType() == PurchaseOrder.TYPE_FREE)
				billdraftidx.setBilltype(Billdraftidx.PURCHASE_FREE);			
			billdraftidx.setA_id(0);
			billdraftidx.setC_id(333);
			billdraftidx.setE_id(userInfor.getJinsuanID());
			billdraftidx.setSout_id(2);
			billdraftidx.setSin_id(2);
			billdraftidx.setAuditman(0);
			billdraftidx.setInputman(userInfor.getJinsuanID());
			billdraftidx.setYsmoney(0);
			billdraftidx.setSsmoney(0);
			billdraftidx.setQuantity(order.getTotalQuantity());
			billdraftidx.setTaxrate(0);
			billdraftidx.setPeriod(0);
			billdraftidx.setBillstates("2");
			billdraftidx.setOrder_id(0);
			billdraftidx.setDepartment_id(0);
//			 billdraftidx.setPosid(0);
			billdraftidx.setRegion_id(0);
//			 billdraftidx.setAuditdate(new Date(0,1,1));
//			 billdraftidx.setSkdate(new Date(0,1,1));
			billdraftidx.setJsye(0);
			billdraftidx.setJsflag("0");
			Date date = new Date();
			DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
			String note = dateFormat.format(date).toString() + " " + order.getSupplier().getName() + " "+ order.getTypeS() + " " + order.getStore().getName()
					+ " (" + order.getComment() + ") ";
			try {
				note += order.getOrderCounter().getName() + "," + order.getOrderAuditor().getName() + ",单号" + orderId;
			} catch (Exception e) {
				loggerLocal.error(e);
			}

			billdraftidx.setInvoice(0);
			billdraftidx.setTranscount(0);
			billdraftidx.setLasttranstime(new Date(0, 1, 1));
			billdraftidx.setGUID(UUID.randomUUID().toString());
			billdraftidx.setInvoiceTotal(0);
			billdraftidx.setInvoiceNO("0");
			billdraftidx.setBusinessType(0);
//			 billdraftidx.setY_id(1);
			billdraftidx.setCurAuditLevel(1);
			billdraftidx.setPRINTCOUNT(0);
			billdraftidx.setPRINTTIME(new Date());
			billdraftidx.setPRINTCOMMENT("");
			billdraftidx.setCanChangeMoney(0);
			billdraftidx.setSizeClassID(-1);
			billdraftidx.setTranFlag(1);
			billdraftidx.setC_ARAPTOTAL(0.00000);
			billdraftidx.setMarketPeriod(0);
			billdraftidx.setsBackGuid("");
			billdraftidx.setMarketCaseId(0);
			billdraftidx.setJsInvoiceTotal(0.00000);
			billdraftidx.setBillDatetime(new Date());
			billdraftidx.setMarketRate(0.00000);
			billdraftidx.setVIPCardID(0);
			billdraftidx.setSummary("");
			billdraftidx.setNote("");

			loggerLocal.info("SupplierService.saveToJinSuan: billdraftidx : " + billdraftidx.getQuantity() + " "
					+ billdraftidx.getNote());

			billdraftidxImpl.save(billdraftidx, false);

			int billid = billdraftidx.getBillid();

			loggerLocal.info("SupplierService.saveToJinSuan: billdraftidx : " + billid);
			double bill_total = 0;
			
			for (PurchaseOrderProduct orderProduct : products) {

				if (order.getType() == PurchaseOrder.TYPE_FREE) {
					bill_total += StoremanagebilldrfDAOImpl.saveBillDtfDetails(orderProduct, billid, orderId, productMap, productMSMap);
				} else 
					bill_total += buymanagebilldrfDAOImpl.saveBillDrfDeails(orderProduct, billid, orderId, productMap, productMSMap);
				
				totalQ += orderProduct.getQuantity();
				totalRow++;
			}
			
			if (totalQ != order.getTotalQuantity()) {
				errorMessage += "将要导入精算的数量和单据原始数量不一致 : 精算数量" + totalQ +",原始数量" + order.getTotalQuantity()+ "<br/>";
			}
			if (totalRow != products.size()) {
				errorMessage += "将要导入精算的单据总条数和单据原始不一致 : 精算条数" + totalRow +",单据条数" + products.size()+ "<br/> 请检查精算单据";
			}	
			
			if (errorMessage.length() > 0)
				note += "** 导入精算有错误 ,核对初始单据 **";
			
			
			billdraftidx.setNote(note);

			billdraftidx.setYsmoney(Common_util.roundDouble(bill_total, 2));
			billdraftidx.setJsye(Common_util.roundDouble(bill_total, 2));
			billdraftidxImpl.update(billdraftidx, false);

			if (errorMessage.length() > 0) {
				response.setFail(errorMessage);
			} else {
				int importTimes = order.getExportNum() + 1;
				order.setExportNum(importTimes);
				
				purchaseOrderDaoImpl.update(order, true);
				response.setSuccess("单据成功导入到精算 : " + orderId);
				response.setReturnValue(orderId);
			}
		} else {
			response.setFail(errorMessage);
		}
		
		return response;
	}

	/**
	 * 下载采购单据
	 * @param order
	 * @param string
	 * @return
	 */
	@Transactional
	public Map<String, Object> generateExcelReport(PurchaseOrder order, String filePath) {
		Map<String,Object> returnMap=new HashMap<String, Object>();   

        
		ByteArrayInputStream byteArrayInputStream;   
		try {     
			HSSFWorkbook wb = null;   
			
			//to get the order information from database
			order = purchaseOrderDaoImpl.get(order.getId(),true);
			purchaseOrderDaoImpl.initialize(order);
			
			SupplierPurchaseOrderTemplate orderTemplate = new SupplierPurchaseOrderTemplate(order, filePath);
			

			wb = orderTemplate.process();

			ByteArrayOutputStream os = new ByteArrayOutputStream();   
			try {   
			    wb.write(os);   
			} catch (IOException e) {   
				loggerLocal.error(e);
		    }   
		    byte[] content = os.toByteArray();   
		    byteArrayInputStream = new ByteArrayInputStream(content);   
		    returnMap.put("stream", byteArrayInputStream);   
         
		    return returnMap;   
		 } catch (Exception ex) {   
			 loggerLocal.error(ex);
		 }   
		return null;   
	}

	/**
	 * 下载供应商采购单据
	 * @param string
	 * @param list
	 * @return
	 */
	public Response generateSupplierOrderExcel(String path, List<PurchaseOrderVO> list) {
		Response response = new Response();
		try {			
			SupplierOrdersTemplate supplierOrdersTemplate = new SupplierOrdersTemplate(list,path);
			HSSFWorkbook wb = supplierOrdersTemplate.process();
			ByteArrayInputStream byteArrayInputStream = ExcelUtil.convertExcelToInputStream(wb);

			response.setReturnValue(byteArrayInputStream);
			response.setReturnCode(Response.SUCCESS);
		} catch (Exception e) {
			loggerLocal.error(e);
			e.printStackTrace();
			response.setFail(e.getMessage());
		}
		return response;
	}
	
}
